package com.jzo2o.customer.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jzo2o.api.customer.dto.response.AddressBookResDTO;
import com.jzo2o.common.enums.EnableStatusEnum;
import com.jzo2o.common.expcetions.BadRequestException;
import com.jzo2o.common.model.PageResult;
import com.jzo2o.common.utils.BeanUtils;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.customer.mapper.AddressBookMapper;
import com.jzo2o.customer.mapper.CommonUserMapper;
import com.jzo2o.customer.model.domain.AddressBook;
import com.jzo2o.customer.model.domain.CommonUser;
import com.jzo2o.customer.model.dto.request.AddressBookPageQueryReqDTO;
import com.jzo2o.customer.model.dto.request.AddressBookUpsertReqDTO;
import com.jzo2o.customer.service.IAddressBookService;
import com.jzo2o.mvc.utils.UserContext;
import com.jzo2o.mysql.utils.PageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 地址薄 服务实现类
 * </p>
 *
 * @author itcast
 * @since 2023-07-06
 */
@Service
public class AddressBookServiceImpl extends ServiceImpl<AddressBookMapper, AddressBook> implements IAddressBookService {
    @Autowired
    private AddressBookMapper addressBookMapper;

    @Override
    public List<AddressBookResDTO> getByUserIdAndCity (Long userId, String city) {

        List<AddressBook> addressBooks = lambdaQuery ()
                .eq (AddressBook::getUserId, userId)
                .eq (AddressBook::getCity, city)
                .list ();
        if (CollUtils.isEmpty (addressBooks)) {
            return new ArrayList<> ();
        }
        return BeanUtils.copyToList (addressBooks, AddressBookResDTO.class);
    }

    @Override
    public PageResult<AddressBookResDTO> addressBookPage (AddressBookPageQueryReqDTO addressBookPageQueryReqDTO) {
        Boolean isAsc1 = addressBookPageQueryReqDTO.getIsAsc1 ();
        Boolean isAsc2 = addressBookPageQueryReqDTO.getIsAsc2 ();
        String orderBy1 = addressBookPageQueryReqDTO.getOrderBy1 ();
        String orderBy2 = addressBookPageQueryReqDTO.getOrderBy2 ();
        Page<AddressBook> addressBookPage = addressBookMapper.selectPage (
                new Page<> (addressBookPageQueryReqDTO.getPageNo (), addressBookPageQueryReqDTO.getPageSize ()),
                Wrappers.<AddressBook>lambdaQuery ()
                        .orderBy (orderBy1 != null, isAsc1, AddressBook::getIsDefault)
                        .orderBy (orderBy2 != null, isAsc2, AddressBook::getUpdateTime)
                        .eq ( AddressBook::getUserId,UserContext.currentUserId ())
        );
//        System.out.println (addressBookPage.getRecords ());
//        List<AddressBookResDTO> addressBookResDTOS = BeanUtils.copyToList (addressBookPage.getRecords (), AddressBookResDTO.class);
        return PageUtils.toPage (addressBookPage, AddressBookResDTO.class);
    }

    @Autowired
    private CommonUserMapper commonUserMapper;

    @Override
    public void saveAddressBook (AddressBookUpsertReqDTO addressBookUpsertReqDTO) {

        String phone = addressBookUpsertReqDTO.getPhone ();
        if (phone == null || phone.length () != 11) {
            throw new BadRequestException ("手机号格式错误");
        }
        Long l = UserContext.currentUserId ();
        if (l == null) {
            throw new BadRequestException ("用户未登录");
        }

        AddressBook addressBook = BeanUtils.copyBean (addressBookUpsertReqDTO, AddressBook.class);
        String location = addressBookUpsertReqDTO.getLocation ();
        if (location != null) {
            String[] split = location.split (",");
            addressBook.setLon (Double.valueOf (split[0]));
            addressBook.setLat (Double.valueOf (split[1]));
        }
        addressBook.setUserId (l);
        this.lambdaUpdate ()
                .set (AddressBook::getIsDefault, EnableStatusEnum.DISABLE.getStatus ())
                .eq (AddressBook::getUserId, UserContext.currentUserId ())
                .update ();
        int insert = addressBookMapper.insert (addressBook);
        if (insert != 1) {
            throw new BadRequestException ("新增失败");
        }
    }

    @Override
    public AddressBookResDTO getAddressBookById (Long id) {
        AddressBook byId = this.getById (id);
        if (byId == null) {
            throw new BadRequestException ("地址不存在");
        }

        if (!Objects.equals (byId.getUserId (), UserContext.currentUserId ())) {
            throw new BadRequestException ("用户错误");
        }
        return BeanUtils.copyBean (byId, AddressBookResDTO.class);
    }

    @Override
    public void updateAddressBook (Long id, AddressBookUpsertReqDTO addressBookUpsertReqDTO) {
        AddressBook byId = this.getById (id);
        if (byId == null) {
            throw new BadRequestException ("地址不存在");
        }
        if (!Objects.equals (byId.getUserId (), UserContext.currentUserId ())) {
            throw new BadRequestException ("用户错误");
        }
        this.lambdaUpdate ()
                .set (AddressBook::getIsDefault, EnableStatusEnum.DISABLE.getStatus ())
                .eq (AddressBook::getUserId, UserContext.currentUserId ())
                .update ();
        BeanUtils.copyProperties (addressBookUpsertReqDTO, byId);
        String location = addressBookUpsertReqDTO.getLocation ();
        if (location != null) {
            String[] split = location.split (",");
            byId.setLon (Double.valueOf (split[0]));
            byId.setLat (Double.valueOf (split[1]));
        }
        int update = addressBookMapper.updateById (byId);
        if (update != EnableStatusEnum.ENABLE.getStatus ()) {
            throw new BadRequestException ("修改失败");
        }
    }

    @Override
    public void setDefaultAddress (Integer flag, Long id) {
        if (flag == null || id == null) {
            throw new BadRequestException ("参数错误");
        }
        if (flag != EnableStatusEnum.DISABLE.getStatus () && flag != EnableStatusEnum.ENABLE.getStatus ()) {
            throw new BadRequestException ("参数错误");
        }
        AddressBook byId = this.getById (id);
        if (byId == null) {
            throw new BadRequestException ("地址不存在");
        }
        if (!Objects.equals (byId.getUserId (), UserContext.currentUserId ())) {
            throw new BadRequestException ("用户错误");
        }
        byId.setIsDefault (flag);
        this.lambdaUpdate ()
                .set (AddressBook::getIsDefault, EnableStatusEnum.DISABLE.getStatus ())
                .eq (AddressBook::getUserId, UserContext.currentUserId ())
                .update ();
        boolean b = this.updateById (byId);
        if (!b) {
            throw new BadRequestException ("修改失败");
        }
    }

    @Override
    public AddressBookResDTO getDefaultAddress (Long id) {
        CommonUser commonUser = commonUserMapper.selectById (id);
        if (commonUser == null) {
            throw new BadRequestException ("用户不存在");
        }
        AddressBook addressBook = this.lambdaQuery ()
                        .eq (AddressBook::getIsDefault, EnableStatusEnum.ENABLE.getStatus ())
                .eq (AddressBook::getUserId, id).one ();
        return BeanUtils.copyBean (addressBook, AddressBookResDTO.class);
    }
}
